package com.gzhryc.weixin.gzh;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.weixin.api.DefaultApiResponse;
import com.gzhryc.weixin.gzh.models.AccessToken;
import com.gzhryc.weixin.gzh.models.MenuEntity;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

/**
 * 微信自定义菜单API接口
 * @author 张浩
 * @version 0.1.0
 */
public class WxMenuApi extends AbsWeixinApi{
	
	public WxMenuApi(AccessToken accessToken) {
		super(accessToken);
	}

	/**
	 * 获取自定义菜单
	 */
	public MenuEntity getMenu(){
		CloseableHttpResponse response = null;
		try {
			if(accessToken != null){
				CloseableHttpClient httpclient = HttpClients.createDefault();
				URI uri = new URIBuilder()
			        .setScheme("https")
			        .setHost("api.weixin.qq.com")
			        .setPath("/cgi-bin/menu/get")
			        .setParameter("access_token",accessToken.getAccess_token())
			        .build();
				HttpGet httpget = new HttpGet(uri);
				response = httpclient.execute(httpget);
				HttpEntity entity = response.getEntity();
				if(entity != null){
					String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
					if(isError(str)){
						DefaultApiResponse result = JsonTools.fromJson(str, DefaultApiResponse.class);
						accessToken.queuePut(result);
					}else{
						MenuEntity menu = JsonTools.fromJson(str, MenuEntity.class);
						return menu;
					}
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 创建菜单
	 * @param menu
	 * @return
	 */
	public boolean createMenu(MenuEntity.Menu menu){
		CloseableHttpResponse response = null;
		try {
			if(accessToken != null){
				CloseableHttpClient httpclient = HttpClients.createDefault();

				URI uri = new URIBuilder()
			        .setScheme("https")
			        .setHost("api.weixin.qq.com")
			        .setPath("/cgi-bin/menu/create")
			        .setParameter("access_token",accessToken.getAccess_token())
			        .build();
				
				StringEntity strEntity = new StringEntity(JsonTools.toJson(menu),
				        ContentType.create("application/json", Consts.UTF_8));

				HttpPost httppost = new HttpPost(uri);
				httppost.setEntity(strEntity);
				
				response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				if(entity != null){
					String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
					DefaultApiResponse result = JsonTools.fromJson(str, DefaultApiResponse.class);
					if(result.getErrcode() == 0){
						return true;
					}else{
						accessToken.queuePut(result);
					}
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
	
	public MenuEntity.Button createButton(String name,String type,String url,String key){
		MenuEntity.Button button = null;
		if("toView".equals(type)){
			try {
				if(key == null){key = "#wechat_redirect";}else{key = key+"#wechat_redirect";}
				URI uri = new URIBuilder()
				    .setScheme("https")
				    .setHost("open.weixin.qq.com")
				    .setPath("/connect/oauth2/authorize")
				    .setParameter("appid",accessToken.getAppid())
				    .setParameter("redirect_uri",url)
				    .setParameter("response_type","code")
				    .setParameter("scope","snsapi_base")
				    .setParameter("state",key)
				    .build();
				button = new MenuEntity.Button();
				button.setName(name);
				button.setType("view");
				button.setUrl(uri.toString());
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}
		}else if("toView2".equals(type)){
			button = new MenuEntity.Button();
			button.setName(name);
			button.setType("view");
			button.setUrl(WxAuthorityApi.getOAuthUrl2(accessToken.getAppid(), url, key));
		}else{
			button = new MenuEntity.Button();
			button.setName(name);
			button.setType(type);
			button.setUrl(url);
			button.setKey(key);
		}
		
		return button;
	}
	
	/**
	 * 删除菜单
	 * @return 是否删除成功
	 */
	public boolean deleteMenu(){
		CloseableHttpResponse response = null;
		try {
			if(accessToken != null){
				CloseableHttpClient httpclient = HttpClients.createDefault();
				URI uri = new URIBuilder()
			        .setScheme("https")
			        .setHost("api.weixin.qq.com")
			        .setPath("/cgi-bin/menu/delete")
			        .setParameter("access_token",accessToken.getAccess_token())
			        .build();
				HttpGet httpget = new HttpGet(uri);
				response = httpclient.execute(httpget);
				HttpEntity entity = response.getEntity();
				if(entity != null){
					String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
					DefaultApiResponse result = JsonTools.fromJson(str, DefaultApiResponse.class);
					if(result.getErrcode() == 0){
						return true;
					}else{
						accessToken.queuePut(result);
					}
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
	
}
